package com.xunyin.nettyV.client;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @Author xunyinyunshang  <3594419785@qq.com>
 * @date 2023-3-16
 * mqtt客户端订阅
 */
public class SubMsg {

    /**
     * 功能描述:连接MQ
     *
     * @param clientId 客户端唯一标识
     * @author zhangpu
     * @date 2022/4/2
     */
    private static MqttClient connect(String clientId) throws MqttException {
        MemoryPersistence persistence = new MemoryPersistence();
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(false);
        connOpts.setConnectionTimeout(10);
        connOpts.setKeepAliveInterval(20);
        //connOpts.setUserName(MqConfig.userName);
        //connOpts.setPassword(MqConfig.passWord.toCharArray());
        MqttClient mqttClient = new MqttClient(MqConfig.broker, clientId, persistence);
        mqttClient.connect(connOpts);
        return mqttClient;
    }


    /**
     * 功能描述:订阅消息
     *
     * @param clientId
     * @param topic
     * @author zhangpu
     * @date 2022/4/2
     */
    public static void subMsg(String clientId, String topic) throws MqttException {
        MqttClient mqttClient = connect(clientId);
        if (mqttClient != null) {
            int[] Qos = {MqConfig.qos};
            String[] topics = {topic};
            mqttClient.subscribe(topics, Qos);
        }
        mqttClient.subscribe(topic, MqConfig.qos, new SubMessageListener());
    }

    public static void main(String[] args) throws MqttException {

        subMsg("testSub", "test-topic");
    }

}
